import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, message } from 'antd';
import { useAntdTable } from '@umijs/hooks';
import request from '@/utils/request';
import SlickTable from '@/components/SlickTable';

function SelectForm({ visiable, close, callback, memberCheck, operMode }) {
  const [searchValue, setSearchValue] = useState('');
  const [selectedRows, setSelectedRows] = useState([]);

  useEffect(() => {
    setSelectedRows(memberCheck || []);
  }, []);

  const submit = () => {
    if (selectedRows.length) {
      callback(selectedRows);
      close();
    } else {
      message.info('你还未选中数据！');
    }
  };

  const getTable = ({ current, pageSize, paramsObj }) => {
    return request('pmc/pms/SysUserController/queryPage', {
      data: {
        pageNum: current,
        pageSize,
        ...paramsObj,
      },
    }).then(res => {
      if (res.success) {
        if (Array.isArray(res.data.records)) {
          return {
            total: res.data.total,
            data: res.data.records.map(val => {
              const { children, ...rest } = val;
              return rest;
            }),
          };
        }
      }
      return {
        total: 0,
        data: [],
      };
    });
  };

  const { tableProps } = useAntdTable(
    params => {
      return getTable({ ...params, pageSize: 5, paramsObj: { paramValue: searchValue } });
    },
    [searchValue],
    {
      defaultPageSize: 5,
    }
  );

  const { pagination, ...restTableProps } = tableProps;

  return (
    <Modal
      title="用户选择"
      width="600px"
      destroyOnClose
      onCancel={close}
      onOk={submit}
      visible={visiable}
    >
      <Input.Search
        placeholder="请输入用户名称进行搜索"
        onSearch={value => setSearchValue(value)}
        style={{ width: '100%' }}
        className="margin-bottom"
      />
      <SlickTable
        rowKey="userId"
        selectedRowKeys={selectedRows.map(row => row.userId)}
        onSelectRow={selectedRows => {
          setSelectedRows(selectedRows);
        }}
        pick={operMode === '2' ? 'radio' : 'checkbox'}
        columns={[
          {
            title: '用户工号',
            dataIndex: 'userCode',
            ellipsis: true,
          },
          {
            title: '用户名称',
            dataIndex: 'userName',
            ellipsis: true,
          },
        ]}
        {...restTableProps}
        data={{
          pagination: {
            ...pagination,
            pageSize: 5,
          },
        }}
      />
    </Modal>
  );
}

export default Form.create()(SelectForm);
